//
//  YWSelectRecordsViewController.m
//  maintain
//
//  Created by Kyo on 16/9/23.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWSelectRecordsViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWCommonTool.h"
#import "NSDate+Additions.h"
#import "MJRefresh.h"
#import "UIScrollView+EmptyDataSet.h"

#import "MBProgressHUD.h"
#import "DOPDropDownMenu.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "YWPostTroubleRecordsCell.h"
#import "YWKeepWatchRecordCell.h"
#import "YWMoreRecordTableViewCell.h"
#import "YWMeterReadingRecordTableViewCell.h"
#import "YWDetectAndUpkeepMissionCell.h"
#import "YWAttendanceRecordsCell.h"
#import "YWDetectAndUpkeepRecordTableViewCell.h"
#import "YWRepairRecordTableViewCell.h"

#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWContactManager.h"
#import "YWDepartment.h"
#import "YWHandler.h"
#import "YWMission.h"
#import "YWEquipmentMaintenanceRecord.h"
#import "YWMeterReadingRecord.h"
#import "YWEquipmentTroubleRecord.h"
#import "YWAttendanceRecord.h"
#import "YWReportTroubleModel.h"
#import "YWTroubleMissionModel.h"

#import "YWKeepWatchMissionManager.h"
#import "YWInspectionMissionManager.h"
#import "YWRecordsManager.h"
#import "YWCirculationOfRecordViewController.h"
#import "YWKeepWatchRecordDetailViewController.h"
#import "YWInspectionRecordDetailViewController.h"
#import "YWMeterReadingDetailRecordTableViewController.h"
#import "YWMissionDetailsViewController.h"
#import "YWMaintenanceRecordDetailTableViewController.h"
#import "YWRecordOfAttendanceTableViewController.h"
#import "YWTemTroubleDetailTableViewController.h"
#import "YWTroubleMissionManager.h"

static CGFloat const kDatePickerViewH = 216;

static NSInteger const KReportTroubleTag = 100;//报障
static NSInteger const KKeepWatchTag = 101;//巡更
static NSInteger const KInspectionTag = 102;//巡查
static NSInteger const KMeterReadingTag = 103;//抄表
static NSInteger const KDetcectionTag = 104;//检测
static NSInteger const KUpkeepTag = 105;//保养
static NSInteger const KTroubleRecordTag = 106;//维修
static NSInteger const KAttendanceTag = 107;//签到


@interface YWSelectRecordsViewController ()<DOPDropDownMenuDataSource,DOPDropDownMenuDelegate,DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>{
    BOOL isShowDatePicker;
    NSInteger page;
    NSString *dateString;
    BOOL needReload;
}

@property (nonatomic, strong) DOPDropDownMenu *menu;
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) UIButton *currenTypeButton;
@property (nonatomic, strong) UIButton *titleViewButton;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;

@property (nonatomic, strong) NSMutableArray *buildingArray;
@property (nonatomic, strong) NSMutableArray *handlerArray;

@property (nonatomic, strong) NSMutableArray *currentDataSource;
@property (nonatomic, assign) NSInteger currentTag;
@property (nonatomic, strong) YWBuilding *currentBuilding;
@property (nonatomic, strong) YWHandler *currentHander;
@property (nonatomic, assign) NSInteger currentStatus;
@property (nonatomic, assign) NSInteger currentType;
@property (nonatomic, assign) NSInteger currentLineId;

@property (nonatomic, strong) NSMutableArray *tableViewDataSource;
@end

@implementation YWSelectRecordsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.navigationItem.titleView = self.titleViewButton;
    
    [self initDefaultData];
    // 创建menu 第一次显示 不会调用点击代理，可以用这个手动调用
    if (_currentDataSource.count) {
        [self.menu selectDefalutIndexPath];
    }
    [self setupTableView];
}

- (void)initDefaultData{
    page = 1;
    needReload = YES;
    _currentTag = KReportTroubleTag;
    _currentBuilding = self.buildingArray.count ? self.buildingArray[0] : nil;
    _currentHander = nil;
    _tableViewDataSource = [NSMutableArray array];
    
    NSArray *statusArray = @[@"状态",@"未分配",@"未完成",@"已完成"];
    NSArray *typeArray = @[@"类型",@"易维保报障",@"微信报障",@"网页报障"];
    _currentStatus = -1;
    _currentType = -1;
    if (self.buildingArray.count) {
        _currentDataSource = [NSMutableArray arrayWithObjects:self.buildingArray,self.handlerArray,statusArray,typeArray, nil];
    }
}

- (void)setupDataWithTag:(NSInteger)tag needRequest:(BOOL)needRequest{
    // 数据
    page = 1;
    needReload = YES;
    _currentTag = tag;
    if (_currentBuilding.buildingId.length == 0) {
        _currentBuilding = self.buildingArray.count ? self.buildingArray[0] : nil;
    }

    _currentHander = nil;
    _currentLineId = 0;
    if (needRequest == NO) {
        [self setupHandler];
    }
    
    NSArray *statusArray = nil;
    NSArray *typeArray = nil;
    switch (tag) {
        case KReportTroubleTag:
            //报障
            statusArray = @[@"状态",@"未分配",@"未完成",@"已完成"];
            typeArray = @[@"类型",@"易维保报障",@"微信报障",@"网页报障"];
            _currentDataSource = [NSMutableArray arrayWithObjects:self.buildingArray,self.handlerArray,statusArray,typeArray, nil];
            break;
        case KKeepWatchTag:
            //巡更
            statusArray = @[@"状态",@"未完成",@"未完成(有报障)",@"已完成(有报障)",@"已完成"];
            typeArray = @[@"路线"];
            _currentDataSource = [NSMutableArray arrayWithObjects:self.buildingArray,self.handlerArray,statusArray,typeArray, nil];
            break;
        case KInspectionTag:
            //巡查
            statusArray = @[@"状态",@"未完成",@"未完成(有报障)",@"已完成(有报障)",@"已完成"];
            typeArray = @[@"路线"];
            _currentDataSource = [NSMutableArray arrayWithObjects:self.buildingArray,self.handlerArray,statusArray,typeArray, nil];
            break;
        case KMeterReadingTag:
            //抄表
            statusArray = @[@"类型",@"水表",@"电表",@"燃气表"];
            _currentDataSource = [NSMutableArray arrayWithObjects:self.buildingArray,self.handlerArray,statusArray, nil];
            break;
        case KDetcectionTag:
            //检测
            statusArray = @[@"状态",@"未完成",@"已完成"];
            typeArray = @[@"类型",@"任务型",@"临时型"];
            _currentDataSource = [NSMutableArray arrayWithObjects:self.buildingArray,self.handlerArray,statusArray,typeArray, nil];
            break;
        case KUpkeepTag:
            //保养
            statusArray = @[@"状态",@"未完成",@"已完成"];
            typeArray = @[@"类型",@"任务型",@"临时型"];
            _currentDataSource = [NSMutableArray arrayWithObjects:self.buildingArray,self.handlerArray,statusArray,typeArray, nil];
            break;
        case KTroubleRecordTag:
            //维修
            _currentDataSource = [NSMutableArray arrayWithObjects:self.buildingArray,self.handlerArray, nil];
            break;
        case KAttendanceTag:
            //签到
            statusArray = @[@"状态",@"签到",@"签退"];
            _currentDataSource = [NSMutableArray arrayWithObjects:self.buildingArray,self.handlerArray,statusArray, nil];
            break;
            
        default:
            break;
    }
    if (statusArray) {
        _currentStatus = -1;
    }
    if (typeArray) {
        if ([typeArray[0] isEqualToString:@"类型"] ||[typeArray[0] isEqualToString:@"路线"]) {
            _currentType = -1;
        }else{
            _currentType = 0;
        }
    }
//    if (needRequest) {
//        [self rightNowgoSelect];
//    }
}

- (NSMutableArray *)buildingArray{
    if (!_buildingArray) {
        NSArray *allBuilding = [[YWBuildingManager shareManager] allBuilding];
        _buildingArray = [NSMutableArray array];
        [_buildingArray addObjectsFromArray:allBuilding];
    }
    return _buildingArray;
}
- (NSMutableArray *)handlerArray{
    if (!_handlerArray) {
        _handlerArray = [NSMutableArray array];
        [self setupHandler];
    }
    return _handlerArray;
}

- (void)setupHandler{
    NSArray *alldepartment = [[YWContactManager shareManager] departmentWithHandlersByBuildingId:_currentBuilding.buildingId];
    NSMutableArray *temp = [NSMutableArray array];
    YWDepartment *department = [[YWDepartment alloc] init];
    department.departmentId = -1;
    department.departmentName = @"人员";
    [temp addObject:department];
    [temp addObjectsFromArray:alldepartment];
    [self.handlerArray removeAllObjects];
    [_handlerArray addObjectsFromArray:temp];
}

- (UIButton *)titleViewButton{
    if (!_titleViewButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeSystem];;//[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 135, 30)];
        [button setFrame:CGRectMake(0, 0, 145, 30)];
        NSDateFormatter *formatter = [self dateFormatter];
        NSString *string = [formatter stringFromDate:[NSDate date]];
        [button setTitle:string forState:UIControlStateNormal];
        dateString = string;
        button.titleLabel.font = [UIFont systemFontOfSize:16.0f];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        //button.backgroundColor = [UIColor customRedColor];
        button.clipsToBounds = YES;
        button.layer.cornerRadius = 4.0;
        
        UIImage *btnImage = [UIImage imageNamed:@"dropDown_arrow"];
        btnImage = [btnImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [button setImage:btnImage forState:UIControlStateNormal];
        //button.imageView.contentMode = UIViewContentModeCenter;
        button.imageView.clipsToBounds = NO;
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
        button.imageEdgeInsets = UIEdgeInsetsMake(0, 145-30-10, 0, 0);
        button.titleEdgeInsets = UIEdgeInsetsMake(6, -10, 0, 0);
        [button addTarget:self action:@selector(clickTitleViewEvent:) forControlEvents:UIControlEventTouchUpInside];
        _titleViewButton = button;
    }
    return _titleViewButton;
}

- (NSDateFormatter*)dateFormatter
{
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}

- (DOPDropDownMenu *)menu{
    if (!_menu) {
        DOPDropDownMenu *menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 64+self.headView.frame.size.height) andHeight:44];
        menu.delegate = self;
        menu.dataSource = self;
        _menu = menu;
    }
    return _menu;
}

- (void)setupTableView{
    page = 1;
    [self.datePicker setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, kDatePickerViewH)];
    
    [self.tableView registerClass:[YWPostTroubleRecordsCell class] forCellReuseIdentifier:YWPostTroubleRecordsCellIdentifier];
    [self.tableView registerClass:[YWDetectAndUpkeepMissionCell class] forCellReuseIdentifier:YWDetectAndUpkeepMissionCellIdentifier];
    [self.tableView registerClass:[YWAttendanceRecordsCell class] forCellReuseIdentifier:YWAttendanceRecordsCellIdentifier];
    [self.tableView registerClass:[YWDetectAndUpkeepRecordTableViewCell class] forCellReuseIdentifier:YWDetectAndUpkeepRecordTableViewCellIdentifier];
    [self.tableView registerClass:[YWRepairRecordTableViewCell class] forCellReuseIdentifier:YWRepairRecordTableViewCellIdentifier];
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.sectionFooterHeight = 0.01f;
    self.tableView.tableHeaderView = self.headView;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    //self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
}
//- (void)refreshTop
//{
//    page = 1;
//    [self.tableView.mj_footer resetNoMoreData];
//    [self requestData:YWTableViewFreshTypeDown];
//}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType
{
    if (refreshType == YWTableViewFreshTypeUp) {
        page++;
    }
    needReload = NO;
    [self goSelect];
}

- (UIView *)headView{
    if (!_headView) {
        CGFloat KItemW = (SCREEN_WIDTH-50)/4;
        CGFloat KItemH = 40;
        NSInteger KCountOfRow = 4;
        NSArray *dateSource = @[@"报障",@"巡更",@"巡查",@"抄表",@"检测",@"保养",@"维修",@"签到"];
        CGFloat height = KItemH * ((dateSource.count-1) / KCountOfRow + 1) + 30;
        UIView* headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
        _headView = headView;
        _headView.backgroundColor = [UIColor customBackgroudColor];
        
        [dateSource enumerateObjectsUsingBlock:^(NSString*  _Nonnull type, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton *button = [[UIButton alloc] init];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            button.backgroundColor = [UIColor whiteColor];
            if (idx==0) {
                _currenTypeButton = button;
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                button.backgroundColor = [UIColor customBlueColor];
                button.layer.borderColor = [UIColor customBlueColor].CGColor;
            }else{
                button.layer.borderColor = [UIColor lightGrayColor].CGColor;
            }
            button.tag = 100 + idx;
            button.frame = CGRectMake(KItemW * (idx % KCountOfRow) + (10*((idx % KCountOfRow + 1))), (idx / KCountOfRow) * KItemH + (10*(idx / KCountOfRow)) + 10, KItemW, KItemH);
            button.titleLabel.font = kContentFont;
            button.layer.masksToBounds = YES;
            button.layer.cornerRadius = 4.0;
            button.layer.borderWidth = 1.0;
            
            [button setTitle:type forState:UIControlStateNormal];
            [button addTarget:self action:@selector(clickTypeButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
            [_headView addSubview:button];
        }];
        [_headView addSubview:[YWCommonTool lineOfView:CGRectMake(0, height-1, SCREEN_WIDTH, 0.5)]];
    }
    return _headView;
}


- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu
{
    return _currentDataSource.count;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column
{
    return column<0 ? 0 : [_currentDataSource[column] count];
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column == 0) {
        YWBuilding *building = _currentDataSource[indexPath.column][indexPath.row];
        return building.buildingName;
    } else if (indexPath.column == 1){
        YWDepartment*department = _currentDataSource[indexPath.column][indexPath.row];
        return department.departmentName;
        
    } else if (indexPath.column == 2){
        return _currentDataSource[indexPath.column][indexPath.row];
    }else if (indexPath.column == 3){
        id object = _currentDataSource[indexPath.column][indexPath.row];
        if ([object isKindOfClass:[YWPatrolLineOption class]]) {
            YWPatrolLineOption *patrolLineOption = object;
            return patrolLineOption.patrolLineName;
        }else if ([object isKindOfClass:[YWInspectionLineOption class]]){
            YWInspectionLineOption *inspectionLine = object;
            return inspectionLine.inspectionLineName;
        }
        else{
            return _currentDataSource[indexPath.column][indexPath.row];
        }
    }
    return nil;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfItemsInRow:(NSInteger)row column:(NSInteger)column
{
    if (column==1 && _currentDataSource.count >=2) {
        YWDepartment* department = [_currentDataSource[column] count]-1 >= row ? _currentDataSource[column][row] : nil;
        return department.memberArray.count;
    }
    
    return 0;
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForItemsInRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column==1) {
        YWDepartment*department = _currentDataSource[indexPath.column][indexPath.row];
        YWHandler *handler = department.memberArray[indexPath.item];
        return handler.userName;
    }
    return nil;
}

- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column==0) {
        NSString *currentBuildingId = _currentBuilding.buildingId;
        YWBuilding *building = _currentDataSource[indexPath.column][indexPath.row];
        _currentBuilding = building;
        [self selectBuildingIdRequestLineWith:_currentTag];
        if (![currentBuildingId isEqualToString:building.buildingId]) {
            [self setupDataWithTag:_currentTag needRequest:NO];
            _currentHander = nil;
            [self.menu reloadData];
            [self.menu selectIndexPath:indexPath triggerDelegate:NO];
        }
    }else if (indexPath.column==1){
        if (indexPath.item >= 0) {
            YWDepartment*department = _currentDataSource[indexPath.column][indexPath.row];
            if (department.memberArray.count>0) {
                YWHandler *handler = department.memberArray[indexPath.item];
                _currentHander = handler?:nil;
            }else{
                _currentHander = nil;
            }
        }else{
            _currentHander = nil;
        }
        
    }else if (indexPath.column==2){
        _currentStatus = indexPath.row -1;
    }else {
        id object = _currentDataSource[indexPath.column][indexPath.row];
        if ([object isKindOfClass:[YWPatrolLineOption class]]) {
            YWPatrolLineOption *patrolLineOption = object;
            _currentLineId = patrolLineOption.patrolLineId;
        }else if ([object isKindOfClass:[YWInspectionLineOption class]]){
            YWInspectionLineOption *inspectionLine = object;
            _currentLineId = inspectionLine.inspectionLineId;
        }
        else{
            _currentType = indexPath.row-1;
        }
    }
    needReload = YES;
    page=1;
    if (indexPath.column==1) {
        if (indexPath.row == 0 || indexPath.item >= 0) {
            [self rightNowgoSelect];
        }
    }else{
        [self rightNowgoSelect];
    }
//    if (indexPath.item >= 0) {
//        YWLog(@"点击了 %ld - %ld - %ld 项目",indexPath.column,indexPath.row,indexPath.item);
//    }else {
//        YWLog(@"点击了 %ld - %ld 项目",indexPath.column,indexPath.row);
//    }
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_currentTag == KReportTroubleTag) {
        return  [tableView fd_heightForCellWithIdentifier:YWPostTroubleRecordsCellIdentifier cacheByIndexPath:indexPath configuration:^(YWPostTroubleRecordsCell *cell) {
            cell.fd_enforceFrameLayout = NO;
            cell.reportTrouble = _tableViewDataSource[indexPath.row];
        }];
    }else if (_currentTag == KKeepWatchTag){
        return kLabelH*2 + 10*2;
    }else if (_currentTag == KInspectionTag){
        return kLabelH*2 + 10*2;
    }else if (_currentTag == KMeterReadingTag){
        return 12*2 + 23*4;
    }else if (_currentTag == KDetcectionTag || _currentTag == KUpkeepTag){
        id object = _tableViewDataSource[indexPath.row];
        if ([object isKindOfClass:[YWMaintenanceMission class]]) {
            return [tableView fd_heightForCellWithIdentifier:YWDetectAndUpkeepMissionCellIdentifier cacheByIndexPath:indexPath configuration:^(YWDetectAndUpkeepMissionCell *cell) {
                //cell.fd_enforceFrameLayout = NO;
                YWMaintenanceMission* mission = _tableViewDataSource[indexPath.row];
                cell.maintenanceMission = mission;
            }];
        }else if ([object isKindOfClass:[YWEquipmentMaintenanceRecord class]]){
            return [tableView fd_heightForCellWithIdentifier:YWDetectAndUpkeepRecordTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWDetectAndUpkeepRecordTableViewCell *cell) {
                //cell.fd_enforceFrameLayout = NO;
                YWEquipmentMaintenanceRecord* record = _tableViewDataSource[indexPath.row];
                cell.maintenanceRecord = record;
            }];
        }else{
            return 0;
        }
        
    }else if (_currentTag == KUpkeepTag){
        if (_currentType == 0) {
            return [tableView fd_heightForCellWithIdentifier:YWDetectAndUpkeepMissionCellIdentifier cacheByIndexPath:indexPath configuration:^(YWDetectAndUpkeepMissionCell *cell) {
                //cell.fd_enforceFrameLayout = NO;
                YWMaintenanceMission* mission = _tableViewDataSource[indexPath.row];
                cell.maintenanceMission = mission;
            }];
        }else{
            return [tableView fd_heightForCellWithIdentifier:YWDetectAndUpkeepRecordTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWDetectAndUpkeepRecordTableViewCell *cell) {
                //cell.fd_enforceFrameLayout = NO;
                YWEquipmentMaintenanceRecord* record = _tableViewDataSource[indexPath.row];
                cell.maintenanceRecord = record;
            }];
        }
    }else if (_currentTag == KTroubleRecordTag){
        return [tableView fd_heightForCellWithIdentifier:YWRepairRecordTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWRepairRecordTableViewCell *cell) {
            YWEquipmentTroubleRecord* record = _tableViewDataSource[indexPath.row];
            //cell.fd_enforceFrameLayout = NO;
            cell.troubleRecord = record;
        }];
    }else if (_currentTag == KAttendanceTag){
        return [tableView fd_heightForCellWithIdentifier:YWAttendanceRecordsCellIdentifier cacheByIndexPath:indexPath configuration:^(YWAttendanceRecordsCell *cell) {
            //cell.fd_enforceFrameLayout = NO;
            cell.attendanceRecord = _tableViewDataSource[indexPath.row];
        }];
    }else{
        return 0;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_tableViewDataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_currentTag == KReportTroubleTag) {
        YWPostTroubleRecordsCell *cell = [tableView dequeueReusableCellWithIdentifier:YWPostTroubleRecordsCellIdentifier];
        cell.reportTrouble = _tableViewDataSource[indexPath.row];
        return cell;
    }else if (_currentTag == KKeepWatchTag){
        YWKeepWatchRecordCell *cell = [YWKeepWatchRecordCell cellWithTableView:tableView];
        YWPatrollineRecord *patrollineRecord = _tableViewDataSource[indexPath.row];
        cell.patrollineRecord = patrollineRecord;
        return cell;
    }
    else if (_currentTag == KInspectionTag){
        YWMoreRecordTableViewCell *cell = [YWMoreRecordTableViewCell cellWithTableView:tableView];
        YWInspectionLineRecord *lineRecord = _tableViewDataSource[indexPath.row];
        cell.lineRecord = lineRecord;
        return cell;
    }
    else if (_currentTag == KMeterReadingTag){
        YWMeterReadingRecordTableViewCell *cell = [YWMeterReadingRecordTableViewCell cellWithTableView:tableView];
        cell.meterReadingRecord = _tableViewDataSource[indexPath.row];
        return cell;
    }
    else if (_currentTag == KDetcectionTag || _currentTag == KUpkeepTag){
        id object = _tableViewDataSource[indexPath.row];
        if ([object isKindOfClass:[YWMaintenanceMission class]]) {
            YWDetectAndUpkeepMissionCell *cell = [tableView dequeueReusableCellWithIdentifier:YWDetectAndUpkeepMissionCellIdentifier];
            //cell.fd_enforceFrameLayout = NO;
            YWMaintenanceMission* mission = _tableViewDataSource[indexPath.row];
            cell.maintenanceMission = mission;
            return cell;
        }else if ([object isKindOfClass:[YWEquipmentMaintenanceRecord class]]){
            YWDetectAndUpkeepRecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:YWDetectAndUpkeepRecordTableViewCellIdentifier];
            cell.maintenanceRecord = _tableViewDataSource[indexPath.row];
            return cell;
        }else{
            return [[UITableViewCell alloc] init];
        }
    }
    else if (_currentTag == KTroubleRecordTag){
        YWRepairRecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:YWRepairRecordTableViewCellIdentifier];
        YWEquipmentTroubleRecord* record = _tableViewDataSource[indexPath.row];
        //cell.fd_enforceFrameLayout = NO;
        cell.troubleRecord = record;
        return cell;
    }
    else if (_currentTag == KAttendanceTag){
        YWAttendanceRecordsCell * cell = [tableView dequeueReusableCellWithIdentifier:YWAttendanceRecordsCellIdentifier];
        //cell.fd_enforceFrameLayout = NO;
        cell.attendanceRecord = _tableViewDataSource[indexPath.row];
        return cell;
    }else{
        return [[UITableViewCell alloc] init];
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    return _menu;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    id object = _tableViewDataSource[indexPath.row];
    if ([object isKindOfClass:[YWReportTroubleModel class]]) {
        //报障
//        YWTroubleMission *troubleMission = object;
        YWCirculationOfRecordViewController *circulationDetailVC = [[YWCirculationOfRecordViewController alloc] init];
        YWReportTroubleModel*reportTrouble = (YWReportTroubleModel*)object;
        if (reportTrouble.troubleMission == nil) {
            YWTroubleMissionModel * troubleMissionModel = [[YWTroubleMissionModel alloc] init];
            troubleMissionModel.trouble = reportTrouble;
            circulationDetailVC.troubleMissionModel = troubleMissionModel;
        }else{
            YWTroubleMissionModel * troubleMissionModel = reportTrouble.troubleMission;
            troubleMissionModel.trouble = reportTrouble;
            circulationDetailVC.troubleMissionModel = troubleMissionModel;
        }
        [self.navigationController pushViewController:circulationDetailVC animated:YES];
    }else if ([object isKindOfClass:[YWPatrollineRecord class]]){
        //巡更
        YWPatrollineRecord *patrollineRecord = object;
        YWKeepWatchRecordDetailViewController *recordDetailVC = [[YWKeepWatchRecordDetailViewController alloc] init];
        recordDetailVC.patrolLineRecord = patrollineRecord;
        [self.navigationController pushViewController:recordDetailVC animated:YES];
    }else if ([object isKindOfClass:[YWInspectionLineRecord class]]){
        //巡查
        YWInspectionLineRecord *inspectionLineRecord = object;
        YWInspectionRecordDetailViewController *recordDetailVC = [[YWInspectionRecordDetailViewController alloc] init];
        recordDetailVC.lineRecord = inspectionLineRecord;
        [self.navigationController pushViewController:recordDetailVC animated:YES];
    }else if ([object isKindOfClass:[YWMeterReadingRecord class]]){
        //抄表
        YWMeterReadingRecord *meterRecord = object;
        YWMeterReadingDetailRecordTableViewController *meterReadingVC = [[YWMeterReadingDetailRecordTableViewController alloc] init];
        meterReadingVC.meterReadingRecord = meterRecord;
        [self.navigationController pushViewController:meterReadingVC animated:YES];
        
    }else if ([object isKindOfClass:[YWMaintenanceMission class]]){
        //检测，保养
        YWMaintenanceMission *maintenanceMission = object;
        YWMissionDetailsViewController* missionDetailsVC = [[YWMissionDetailsViewController alloc] init];
        missionDetailsVC.mission = maintenanceMission;
        missionDetailsVC.isFromRecord = YES;
        [self.navigationController pushViewController:missionDetailsVC animated:YES];
    }else if ((_currentTag == KDetcectionTag||_currentTag == KUpkeepTag) && [object isKindOfClass:[YWEquipmentMaintenanceRecord class]]){
        //检测保养记录
        YWEquipmentMaintenanceRecord* record = (YWEquipmentMaintenanceRecord*)object;
        YWMaintenanceRecordDetailTableViewController* maintenanceVC = [[YWMaintenanceRecordDetailTableViewController alloc] init];
        record.maintenanceTypeId = record.maintenanceTypeId;
        maintenanceVC.maintenanceRecord = record;
        [self.navigationController pushViewController:maintenanceVC animated:YES];
    }else if (_currentTag == KTroubleRecordTag && [object isKindOfClass:[YWEquipmentTroubleRecord class]]){
        //维修记录
        YWEquipmentTroubleRecord *troubleRecord = object;
        if (troubleRecord.troubleId<=0) {
            YWTemTroubleDetailTableViewController *tempTroubleVC = [[YWTemTroubleDetailTableViewController alloc] init];
            tempTroubleVC.troubleRecord = troubleRecord;
            [self.navigationController pushViewController:tempTroubleVC animated:YES];
        }else if (troubleRecord.troubleId>0){
            YWCirculationOfRecordViewController *circulationDetailVC = [[YWCirculationOfRecordViewController alloc] init];
            YWTroubleMissionModel *troubleMissionModel = [[YWTroubleMissionManager shareManager] troubleMissionModelWithTroubleId:troubleRecord.troubleId];
            if (troubleMissionModel == nil) {
                troubleMissionModel = [[YWTroubleMissionModel alloc] init];
                YWReportTroubleModel * reportTrouble = [[YWReportTroubleModel alloc] init];
                reportTrouble.troubleId = troubleRecord.troubleId;
                troubleMissionModel.trouble = reportTrouble;
                troubleMissionModel.troubleStatus = YWTroubleMissionStatusFinish;
            }
            circulationDetailVC.troubleMissionModel = troubleMissionModel;
            [self.navigationController pushViewController:circulationDetailVC animated:YES];
        }else{
            [YWCommonTool showTextHUDWithContent:@"未找到任务"];
        }
        
    }else if ([object isKindOfClass:[YWAttendanceRecord class]]){
        //签到
        YWAttendanceRecord *attendanceRecord = object;
        YWRecordOfAttendanceTableViewController* attendanceRecordVC = [[YWRecordOfAttendanceTableViewController alloc] init];
        attendanceRecordVC.attendanceRecord = attendanceRecord;
        [self.navigationController pushViewController:attendanceRecordVC animated:YES];
    }
}

- (void)clickTitleViewEvent:(id)sender{
    if (isShowDatePicker) {
        [self resetDatePicker];
    }else{
        isShowDatePicker = YES;
        [UIView animateWithDuration:0.25 animations:^{
            self.datePicker.frame=CGRectMake(0, SCREEN_HEIGHT-216, SCREEN_WIDTH, 216);
        }];
    }
}

- (void)clickTypeButtonEvent:(UIButton*)button{
    NSInteger tag = button.tag;
    if (_currenTypeButton.tag != tag) {
        [_currenTypeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _currenTypeButton.backgroundColor = [UIColor whiteColor];
        _currenTypeButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _currenTypeButton = button;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        button.layer.borderColor = [UIColor customBlueColor].CGColor;
        
        if (_currentBuilding.buildingId.length == 0) {
            return;
        }
        
        [self setupDataWithTag:tag needRequest:YES];
        [_menu selectDefalutIndexPath];
        [_menu reloadData];
    }
}

- (void)selectBuildingIdRequestLineWith:(NSInteger)buttonTag{
    YWWeakSelf(weakSelf);
    if (buttonTag == KKeepWatchTag && _currentBuilding) {
        [[YWKeepWatchMissionManager shareManager] requestPatrolLineWithBuildingId:_currentBuilding.buildingId Complete:^(NSArray *lineArray) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (lineArray.count) {
                    [weakSelf.currentDataSource removeLastObject];
                    NSMutableArray *temp = [NSMutableArray array];
                    YWPatrolLineOption *lineOption = [[YWPatrolLineOption alloc] init];
                    lineOption.patrolLineName = @"路线";
                    lineOption.patrolLineId = -1;
                    [temp addObject:lineOption];
                    [temp addObjectsFromArray:lineArray];
                    [weakSelf.currentDataSource addObject:temp];
                    YWPatrolLineOption *lastLineOption = [temp firstObject];
                    weakSelf.currentLineId = lastLineOption.patrolLineId;
//                    [weakSelf.menu reloadData];
                }
            });
        }];
    }else if (buttonTag == KInspectionTag && _currentBuilding){
        [[YWInspectionMissionManager shareManager] requestInspectionLineWithBuildingId:_currentBuilding.buildingId Complete:^(NSArray *lineArray) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (lineArray.count) {
                    [weakSelf.currentDataSource removeLastObject];
                    NSMutableArray *temp = [NSMutableArray array];
                    YWInspectionLineOption *lineOption = [[YWInspectionLineOption alloc] init];
                    lineOption.inspectionLineName = @"路线";
                    lineOption.inspectionLineId = -1;
                    [temp addObject:lineOption];
                    [temp addObjectsFromArray:lineArray];
                    [weakSelf.currentDataSource addObject:temp];
                    YWInspectionLineOption *lastLineOption = [temp firstObject];
                    weakSelf.currentLineId = lastLineOption.inspectionLineId;
//                    [weakSelf.menu reloadData];
                }
            });
        }];
    }
}

- (void)rightNowgoSelect{
    if (isShowDatePicker) {
        [self resetDatePicker];
    }
    [self goSelect];
}

- (void)goSelect{
    if (_currentBuilding.buildingId.length == 0) {
        return;
    }
    YWWeakSelf(weakSelf);
    if (page==1) {
        //上拉page>1,不显示转圈
        [self.HUD show:YES];
    }
    if (_currentTag == KReportTroubleTag) {
        //查询报障
        [[YWRecordsManager shareManager] selectPostTroubleRecord:page date:dateString buildingId:_currentBuilding.buildingId reporterId:_currentHander.uniqueId status:_currentStatus source:_currentType complete:^(NSArray *recordArray) {
            [weakSelf.HUD hide:YES];
            [weakSelf.tableView.mj_footer endRefreshing];
            if (needReload) {
                [weakSelf.tableViewDataSource removeAllObjects];
            }
            [weakSelf.tableViewDataSource addObjectsFromArray:recordArray];
            [weakSelf.tableView reloadData];
        }];
    }else if (_currentTag == KKeepWatchTag){
        //查询巡更
        [[YWRecordsManager shareManager] selectKeepWatchRecord:page date:dateString buildingId:_currentBuilding.buildingId executorId:_currentHander.uniqueId status:_currentStatus lineId:_currentLineId complete:^(NSArray *recordArray) {
            [weakSelf.HUD hide:YES];
            [weakSelf.tableView.mj_footer endRefreshing];
            if (needReload) {
                [weakSelf.tableViewDataSource removeAllObjects];
            }
            [weakSelf.tableViewDataSource addObjectsFromArray:recordArray];
            [weakSelf.tableView reloadData];
        }];
    }else if (_currentTag == KInspectionTag){
        //查询巡查
        [[YWRecordsManager shareManager] selectInspectionRecord:page date:dateString buildingId:_currentBuilding.buildingId executorId:_currentHander.uniqueId status:_currentStatus lineId:_currentLineId complete:^(NSArray *recordArray) {
            [weakSelf.HUD hide:YES];
            [weakSelf.tableView.mj_footer endRefreshing];
            if (needReload) {
                [weakSelf.tableViewDataSource removeAllObjects];
            }
            [weakSelf.tableViewDataSource addObjectsFromArray:recordArray];
            [weakSelf.tableView reloadData];
        }];
    }else if (_currentTag == KMeterReadingTag){
        //查询抄表
        [[YWRecordsManager shareManager] selectMeterReadingRecord:page date:dateString buildingId:_currentBuilding.buildingId executorId:_currentHander.uniqueId status:_currentStatus complete:^(NSArray *recordArray) {
            [weakSelf.HUD hide:YES];
            [weakSelf.tableView.mj_footer endRefreshing];
            if (needReload) {
                [_tableViewDataSource removeAllObjects];
            }
            [weakSelf.tableViewDataSource addObjectsFromArray:recordArray];
            [weakSelf.tableView reloadData];
        }];
    }else if (_currentTag == KDetcectionTag){
        //查询检测
        if (_currentType == -1 || _currentType ==0) {
            [[YWRecordsManager shareManager] selectDetectRecord:page date:dateString buildingId:_currentBuilding.buildingId executorId:_currentHander.uniqueId status:_currentStatus type:_currentType complete:^(NSArray *recordArray) {
                [weakSelf.HUD hide:YES];
                [weakSelf.tableView.mj_footer endRefreshing];
                if (needReload) {
                    [weakSelf.tableViewDataSource removeAllObjects];
                }
                [weakSelf.tableViewDataSource addObjectsFromArray:recordArray];
                [weakSelf.tableView reloadData];
            }];
        }else{
            //查询临时检测
            [[YWRecordsManager shareManager] selectTempDetectRecord:page date:dateString buildingId:_currentBuilding.buildingId executorId:_currentHander.uniqueId status:_currentStatus type:_currentType complete:^(NSArray *recordArray) {
                [weakSelf.HUD hide:YES];
                [weakSelf.tableView.mj_footer endRefreshing];
                if (needReload) {
                    [weakSelf.tableViewDataSource removeAllObjects];
                }
                [weakSelf.tableViewDataSource addObjectsFromArray:recordArray];
                [weakSelf.tableView reloadData];
            }];
        }
    }else if (_currentTag == KUpkeepTag){
        //查询保养
        if (_currentType == -1 || _currentType ==0) {
            [[YWRecordsManager shareManager] selectUpkeepRecord:page date:dateString buildingId:_currentBuilding.buildingId executorId:_currentHander.uniqueId status:_currentStatus type:_currentType complete:^(NSArray *recordArray) {
                [weakSelf.HUD hide:YES];
                [weakSelf.tableView.mj_footer endRefreshing];
                if (needReload) {
                    [weakSelf.tableViewDataSource removeAllObjects];
                }
                [weakSelf.tableViewDataSource addObjectsFromArray:recordArray];
                [weakSelf.tableView reloadData];
            }];
        }else{
            //查询临时保养
            [[YWRecordsManager shareManager] selectTempUpkeepRecord:page date:dateString buildingId:_currentBuilding.buildingId executorId:_currentHander.uniqueId status:_currentStatus type:_currentType complete:^(NSArray *recordArray) {
                [weakSelf.HUD hide:YES];
                [weakSelf.tableView.mj_footer endRefreshing];
                if (needReload) {
                    [weakSelf.tableViewDataSource removeAllObjects];
                }
                [weakSelf.tableViewDataSource addObjectsFromArray:recordArray];
                [weakSelf.tableView reloadData];
            }];
        }
    }else if (_currentTag == KTroubleRecordTag){
        //查询维修
        [[YWRecordsManager shareManager] selectTroubleRecord:page date:dateString buildingId:_currentBuilding.buildingId executorId:_currentHander.uniqueId complete:^(NSArray *recordArray) {
            [weakSelf.HUD hide:YES];
            [weakSelf.tableView.mj_footer endRefreshing];
            if (needReload) {
                [weakSelf.tableViewDataSource removeAllObjects];
            }
            [weakSelf.tableViewDataSource addObjectsFromArray:recordArray];
            [weakSelf.tableView reloadData];
        }];
    }else if (_currentTag == KAttendanceTag){
        //查询签到
        [[YWRecordsManager shareManager] selectAttendanceRecord:page date:dateString buildingId:_currentBuilding.buildingId executorId:_currentHander.uniqueId type:_currentStatus complete:^(NSArray *recordArray) {
            [weakSelf.HUD hide:YES];
            [weakSelf.tableView.mj_footer endRefreshing];
            if (needReload) {
                [weakSelf.tableViewDataSource removeAllObjects];
            }
            [weakSelf.tableViewDataSource addObjectsFromArray:recordArray];
            [weakSelf.tableView reloadData];
        }];
    }
}

-(UIDatePicker *)datePicker{
    if (!_datePicker) {
        _datePicker=[[UIDatePicker alloc]init];
        [_datePicker setBackgroundColor:[UIColor whiteColor]];
        _datePicker.locale =[NSLocale localeWithLocaleIdentifier:@"zh"];
        _datePicker.datePickerMode = UIDatePickerModeDate;
        _datePicker.minimumDate = [NSDate dateWithDaysBeforeNow:6];
        _datePicker.maximumDate = [NSDate date];
        [_datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
        [self.navigationController.view addSubview:_datePicker];
    }
    return _datePicker;
}
-(void)dateChanged:(id)sender{
    UIDatePicker *picker = (UIDatePicker*)sender;
    NSDate *date = picker.date;
    NSDateFormatter *formatter = [self dateFormatter];
    NSString *string = [formatter stringFromDate:date];
    [_titleViewButton setTitle:string forState:UIControlStateNormal];
    if (![dateString isEqualToString:string]) {
        dateString = string;
        needReload = YES;
        page = 1;
        [self rightNowgoSelect];
    }
}

-(void)resetDatePicker{
    isShowDatePicker = NO;
    [UIView animateWithDuration:0.25 animations:^{
        [_datePicker setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, kDatePickerViewH)];
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
    if (isShowDatePicker) {
        [self resetDatePicker];
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self resetDatePicker];
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = @"查询中";
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
